<template>
  <div class="cashier-manage-page">
    <!-- 收银概览卡片 -->
    <el-row :gutter="20" class="overview-cards">
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon sales">
              <el-icon size="24"><TrendCharts /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-value">¥{{ formatNumber(cashierOverview.todaySales) }}</div>
              <div class="card-label">今日销售额</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon orders">
              <el-icon size="24"><Document /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-value">{{ cashierOverview.todayOrders }}</div>
              <div class="card-label">今日订单数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon customers">
              <el-icon size="24"><User /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-value">{{ cashierOverview.todayCustomers }}</div>
              <div class="card-label">今日客流量</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon average">
              <el-icon size="24"><Money /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-value">¥{{ formatNumber(cashierOverview.averageOrder) }}</div>
              <div class="card-label">平均客单价</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 收银管理主区域 -->
    <el-card>
      <template #header>
        <div class="page-header">
          <h3>收银管理</h3>
          <div class="header-actions">
            <el-button type="success" @click="openCashier">
              <el-icon><Plus /></el-icon>
              打开收银台
            </el-button>
            <el-button type="primary" @click="showStatistics">
              <el-icon><TrendCharts /></el-icon>
              销售统计
            </el-button>
            <el-button type="warning" @click="showRefundDialog">
              <el-icon><RefreshLeft /></el-icon>
              退款处理
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :model="searchForm" inline>
          <el-form-item label="订单号">
            <el-input v-model="searchForm.orderNo" placeholder="请输入订单号" clearable />
          </el-form-item>
          <el-form-item label="收银员">
            <el-select v-model="searchForm.cashier" placeholder="请选择收银员" clearable>
              <el-option label="收银员001" value="收银员001" />
              <el-option label="收银员002" value="收银员002" />
              <el-option label="收银员003" value="收银员003" />
            </el-select>
          </el-form-item>
          <el-form-item label="支付方式">
            <el-select v-model="searchForm.paymentMethod" placeholder="请选择支付方式" clearable>
              <el-option label="现金支付" value="cash" />
              <el-option label="刷卡支付" value="card" />
              <el-option label="支付宝" value="alipay" />
              <el-option label="微信支付" value="wechat" />
            </el-select>
          </el-form-item>
          <el-form-item label="日期范围">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格区域 -->
      <el-table :data="tableData" v-loading="loading" stripe>
        <el-table-column prop="orderNo" label="订单号" width="150" />
        <el-table-column prop="createTime" label="收银时间" width="180" />
        <el-table-column prop="cashier" label="收银员" width="120" />
        <el-table-column prop="itemCount" label="商品数量" width="100" />
        <el-table-column prop="totalAmount" label="商品总额" width="120">
          <template #default="{ row }">
            ¥{{ formatNumber(row.totalAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="discountAmount" label="优惠金额" width="120">
          <template #default="{ row }">
            <span class="discount">-¥{{ formatNumber(row.discountAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="finalAmount" label="实收金额" width="120">
          <template #default="{ row }">
            <span class="amount">¥{{ formatNumber(row.finalAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="paymentMethod" label="支付方式" width="120">
          <template #default="{ row }">
            <el-tag :type="getPaymentMethodType(row.paymentMethod)">
              {{ getPaymentMethodName(row.paymentMethod) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">
              查看
            </el-button>
            <el-button type="success" size="small" @click="handleReprint(row)">
              重打小票
            </el-button>
            <el-button 
              v-if="row.status === '已完成'" 
              type="warning" 
              size="small" 
              @click="handleRefund(row)"
            >
              退款
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="订单详情"
      width="800px"
    >
      <div v-if="currentOrder">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单号">{{ currentOrder.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="收银时间">{{ currentOrder.createTime }}</el-descriptions-item>
          <el-descriptions-item label="收银员">{{ currentOrder.cashier }}</el-descriptions-item>
          <el-descriptions-item label="支付方式">
            <el-tag :type="getPaymentMethodType(currentOrder.paymentMethod)">
              {{ getPaymentMethodName(currentOrder.paymentMethod) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="商品总额">¥{{ formatNumber(currentOrder.totalAmount) }}</el-descriptions-item>
          <el-descriptions-item label="优惠金额">-¥{{ formatNumber(currentOrder.discountAmount) }}</el-descriptions-item>
          <el-descriptions-item label="实收金额">¥{{ formatNumber(currentOrder.finalAmount) }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(currentOrder.status)">
              {{ currentOrder.status }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>

        <el-divider>商品明细</el-divider>
        <el-table :data="currentOrder.items" border>
          <el-table-column prop="name" label="商品名称" width="200" />
          <el-table-column prop="code" label="商品编码" width="120" />
          <el-table-column prop="salePrice" label="单价" width="100">
            <template #default="{ row }">¥{{ formatNumber(row.salePrice) }}</template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量" width="80" />
          <el-table-column prop="total" label="小计" width="120">
            <template #default="{ row }">¥{{ formatNumber(row.salePrice * row.quantity) }}</template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>

    <!-- 退款对话框 -->
    <el-dialog
      v-model="refundDialogVisible"
      title="退款处理"
      width="600px"
    >
      <el-form
        ref="refundFormRef"
        :model="refundForm"
        :rules="refundRules"
        label-width="100px"
      >
        <el-form-item label="订单号">
          <el-input v-model="refundForm.orderNo" disabled />
        </el-form-item>
        
        <el-form-item label="原支付金额">
          <el-input :value="'¥' + formatNumber(refundForm.originalAmount)" disabled />
        </el-form-item>

        <el-form-item label="退款金额" prop="refundAmount">
          <el-input-number 
            v-model="refundForm.refundAmount" 
            :min="0" 
            :max="refundForm.originalAmount"
            :precision="2"
            style="width: 100%"
            placeholder="请输入退款金额"
          />
        </el-form-item>

        <el-form-item label="退款方式" prop="refundMethod">
          <el-select v-model="refundForm.refundMethod" placeholder="请选择退款方式" style="width: 100%">
            <el-option label="原路退回" value="original" />
            <el-option label="现金退款" value="cash" />
            <el-option label="银行卡退款" value="card" />
          </el-select>
        </el-form-item>

        <el-form-item label="退款原因" prop="reason">
          <el-select v-model="refundForm.reason" placeholder="请选择退款原因" style="width: 100%">
            <el-option label="商品质量问题" value="quality" />
            <el-option label="商品损坏" value="damage" />
            <el-option label="客户不满意" value="dissatisfied" />
            <el-option label="重复支付" value="duplicate" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="refundForm.remark" 
            type="textarea" 
            :rows="3"
            placeholder="请输入退款备注" 
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="refundDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleRefundSubmit" :loading="refundLoading">
          确认退款
        </el-button>
      </template>
    </el-dialog>

    <!-- 销售统计对话框 -->
    <el-dialog
      v-model="statisticsDialogVisible"
      title="销售统计"
      width="1000px"
    >
      <el-tabs v-model="activeStatisticsTab">
        <el-tab-pane label="销售趋势" name="trend">
          <div class="statistics-content">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-card>
                  <template #header>
                    <span>今日销售趋势</span>
                  </template>
                  <div class="chart-container">
                    <div class="chart-placeholder">
                      <el-icon size="48"><TrendCharts /></el-icon>
                      <p>销售趋势图表</p>
                    </div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="12">
                <el-card>
                  <template #header>
                    <span>支付方式统计</span>
                  </template>
                  <div class="chart-container">
                    <div class="chart-placeholder">
                      <el-icon size="48"><PieChart /></el-icon>
                      <p>支付方式饼图</p>
                    </div>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="商品销售排行" name="ranking">
          <el-table :data="salesRanking" border>
            <el-table-column prop="rank" label="排名" width="80" />
            <el-table-column prop="name" label="商品名称" width="200" />
            <el-table-column prop="code" label="商品编码" width="120" />
            <el-table-column prop="salesCount" label="销售数量" width="120" />
            <el-table-column prop="salesAmount" label="销售金额" width="120">
              <template #default="{ row }">¥{{ formatNumber(row.salesAmount) }}</template>
            </el-table-column>
            <el-table-column prop="profit" label="利润" width="120">
              <template #default="{ row }">¥{{ formatNumber(row.profit) }}</template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        
        <el-tab-pane label="收银员业绩" name="performance">
          <el-table :data="cashierPerformance" border>
            <el-table-column prop="cashier" label="收银员" width="120" />
            <el-table-column prop="orderCount" label="订单数量" width="120" />
            <el-table-column prop="salesAmount" label="销售金额" width="120">
              <template #default="{ row }">¥{{ formatNumber(row.salesAmount) }}</template>
            </el-table-column>
            <el-table-column prop="averageOrder" label="平均客单价" width="120">
              <template #default="{ row }">¥{{ formatNumber(row.averageOrder) }}</template>
            </el-table-column>
            <el-table-column prop="refundCount" label="退款次数" width="120" />
            <el-table-column prop="refundAmount" label="退款金额" width="120">
              <template #default="{ row }">¥{{ formatNumber(row.refundAmount) }}</template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 响应式数据
const loading = ref(false)
const viewDialogVisible = ref(false)
const refundDialogVisible = ref(false)
const statisticsDialogVisible = ref(false)
const refundLoading = ref(false)
const activeStatisticsTab = ref('trend')
const refundFormRef = ref()
const currentOrder = ref(null)

// 收银概览数据
const cashierOverview = reactive({
  todaySales: 25680.50,
  todayOrders: 156,
  todayCustomers: 142,
  averageOrder: 180.85
})

// 搜索表单
const searchForm = reactive({
  orderNo: '',
  cashier: '',
  paymentMethod: '',
  dateRange: []
})

// 退款表单
const refundForm = reactive({
  orderNo: '',
  originalAmount: 0,
  refundAmount: 0,
  refundMethod: '',
  reason: '',
  remark: ''
})

// 表单验证规则
const refundRules = {
  refundAmount: [
    { required: true, message: '请输入退款金额', trigger: 'blur' }
  ],
  refundMethod: [
    { required: true, message: '请选择退款方式', trigger: 'change' }
  ],
  reason: [
    { required: true, message: '请选择退款原因', trigger: 'change' }
  ]
}

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表格数据
const tableData = ref([
  {
    id: 1,
    orderNo: 'R20240115001',
    createTime: '2024-01-15 14:30:25',
    cashier: '收银员001',
    itemCount: 3,
    totalAmount: 125.50,
    discountAmount: 5.00,
    finalAmount: 120.50,
    paymentMethod: 'alipay',
    status: '已完成',
    items: [
      { name: '可口可乐', code: 'P004', salePrice: 3.5, quantity: 2 },
      { name: '洗发水', code: 'P005', salePrice: 29.9, quantity: 1 },
      { name: 'Nike运动鞋', code: 'P003', salePrice: 899, quantity: 1 }
    ]
  },
  {
    id: 2,
    orderNo: 'R20240115002',
    createTime: '2024-01-15 14:25:10',
    cashier: '收银员002',
    itemCount: 2,
    totalAmount: 899.00,
    discountAmount: 0,
    finalAmount: 899.00,
    paymentMethod: 'cash',
    status: '已完成',
    items: [
      { name: 'Nike运动鞋', code: 'P003', salePrice: 899, quantity: 1 }
    ]
  },
  {
    id: 3,
    orderNo: 'R20240115003',
    createTime: '2024-01-15 14:20:05',
    cashier: '收银员001',
    itemCount: 1,
    totalAmount: 5999.00,
    discountAmount: 200.00,
    finalAmount: 5799.00,
    paymentMethod: 'card',
    status: '已完成',
    items: [
      { name: 'iPhone 15', code: 'P001', salePrice: 5999, quantity: 1 }
    ]
  }
])

// 销售排行数据
const salesRanking = ref([
  { rank: 1, name: '可口可乐', code: 'P004', salesCount: 156, salesAmount: 546.00, profit: 109.20 },
  { rank: 2, name: '洗发水', code: 'P005', salesCount: 45, salesAmount: 1345.50, profit: 269.10 },
  { rank: 3, name: 'Nike运动鞋', code: 'P003', salesCount: 12, salesAmount: 10788.00, profit: 2157.60 },
  { rank: 4, name: 'iPhone 15', code: 'P001', salesCount: 3, salesAmount: 17997.00, profit: 3599.40 },
  { rank: 5, name: 'MacBook Pro', code: 'P002', salesCount: 1, salesAmount: 12999.00, profit: 2599.80 }
])

// 收银员业绩数据
const cashierPerformance = ref([
  { cashier: '收银员001', orderCount: 89, salesAmount: 15680.50, averageOrder: 176.18, refundCount: 2, refundAmount: 120.00 },
  { cashier: '收银员002', orderCount: 67, salesAmount: 10000.00, averageOrder: 149.25, refundCount: 1, refundAmount: 50.00 }
])

// 计算属性
const getPaymentMethodType = (method) => {
  const typeMap = {
    'cash': 'success',
    'card': 'primary',
    'alipay': 'warning',
    'wechat': 'info'
  }
  return typeMap[method] || 'info'
}

const getPaymentMethodName = (method) => {
  const nameMap = {
    'cash': '现金支付',
    'card': '刷卡支付',
    'alipay': '支付宝',
    'wechat': '微信支付'
  }
  return nameMap[method] || method
}

const getStatusType = (status) => {
  const statusMap = {
    '已完成': 'success',
    '已退款': 'warning',
    '部分退款': 'info'
  }
  return statusMap[status] || 'info'
}

// 方法
const formatNumber = (value) => {
  if (typeof value === 'number') {
    return value.toLocaleString()
  }
  return value
}

const loadData = () => {
  loading.value = true
  setTimeout(() => {
    pagination.total = tableData.value.length
    loading.value = false
  }, 500)
}

const handleSearch = () => {
  pagination.currentPage = 1
  loadData()
}

const handleReset = () => {
  Object.assign(searchForm, {
    orderNo: '',
    cashier: '',
    paymentMethod: '',
    dateRange: []
  })
  handleSearch()
}

const handleView = (row) => {
  currentOrder.value = row
  viewDialogVisible.value = true
}

const handleReprint = (row) => {
  ElMessage.success(`重打小票: ${row.orderNo}`)
}

const handleRefund = (row) => {
  Object.assign(refundForm, {
    orderNo: row.orderNo,
    originalAmount: row.finalAmount,
    refundAmount: row.finalAmount,
    refundMethod: '',
    reason: '',
    remark: ''
  })
  refundDialogVisible.value = true
}

const showRefundDialog = () => {
  ElMessage.info('请先选择要退款的订单')
}

const openCashier = () => {
  ElMessage.info('跳转到收银台页面')
}

const showStatistics = () => {
  statisticsDialogVisible.value = true
}

const handleRefundSubmit = async () => {
  if (!refundFormRef.value) return

  try {
    await refundFormRef.value.validate()
    refundLoading.value = true

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))

    // 更新订单状态
    const order = tableData.value.find(item => item.orderNo === refundForm.orderNo)
    if (order) {
      if (refundForm.refundAmount === refundForm.originalAmount) {
        order.status = '已退款'
      } else {
        order.status = '部分退款'
      }
    }

    ElMessage.success('退款处理成功')
    refundDialogVisible.value = false
    loadData()
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    refundLoading.value = false
  }
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadData()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadData()
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.cashier-manage-page {
  padding: 0;
}

.overview-cards {
  margin-bottom: 20px;
}

.overview-card {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-content {
  display: flex;
  align-items: center;
}

.card-icon {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  color: white;
}

.card-icon.sales {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.card-icon.orders {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.card-icon.customers {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.card-icon.average {
  background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
}

.card-info {
  flex: 1;
}

.card-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.card-label {
  font-size: 14px;
  color: #909399;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h3 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.search-area {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 4px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.discount {
  color: #67c23a;
}

.amount {
  color: #f56c6c;
  font-weight: 600;
}

.statistics-content {
  padding: 20px 0;
}

.chart-container {
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.chart-placeholder {
  text-align: center;
  color: #909399;
}

.chart-placeholder p {
  margin-top: 10px;
  font-size: 14px;
}
</style>
